package com.mhl.campuscabinet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Bundle;
import android.os.Looper;
import android.widget.Toast;

import com.mhl.adapter.ProductAdapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.Product;
import com.mhl.entity.User;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyStarActivity extends AppCompatActivity {

    private List<Product> productList = new ArrayList<>();
    private ProductAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_star);
        loadStarProduct();
        //test();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycle_view);
        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new ProductAdapter(productList, this);
        recyclerView.setAdapter(adapter);
    }

    // 加载我收藏的但没被卖出去的商品列表
    private void loadStarProduct() {
        JSONObject userJson = new JSONObject();

        try {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            userJson.put("user_id", User.getInstance().getUserId());
            String json = userJson.toString();
            RequestBody requestBody = RequestBody.Companion.create(json, mediaType);
            //todo fill true ip
            OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp() + "user/merchandise/star", requestBody, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    System.out.println(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String registerItemsString = response.body().string();
                    try {

                        int state = 1;
                        try {
                            JSONObject errcodeJson = new JSONObject(registerItemsString);
                            state = errcodeJson.getInt("errcode");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        Looper.prepare();
                        if (state != 0) {
                            Toast.makeText(MyStarActivity.this, "Can't load my star list", Toast.LENGTH_SHORT).show();
                        } else {
                            JSONObject respose = new JSONObject(registerItemsString);
                            JSONObject data = respose.getJSONObject("data");
                            JSONArray merchandise = data.getJSONArray("merchandise");
                            for (int i = 0; i < merchandise.length(); i++) {
                                JSONObject item = merchandise.getJSONObject(i);
                                Product product = new Product();
                                product.setPrice(item.getDouble("pre_price"));
                                product.setName(item.getString("name"));
                                //product.setDescription(item.getString("des"));

                                JSONArray urls = item.getJSONArray("url_list");
                                product.setURL(urls.getString(0));
                                //product.setImageId(item.getInt("imgId"));

                                product.setId(item.getInt("id"));
                                productList.add(product);

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        adapter.notifyDataSetChanged();
                                    }
                                });
                            }

//                            adapter.notifyDataSetChanged();
                            //adapter.notifyItemInserted(productList.size());
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Looper.loop();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 测试用例
    private void test() {
        productList.clear();
        for(int i = 0; i < 7; i++) {
            Product product1 = new Product();
            product1.setName("1");
            product1.setPrice(200);
            product1.setURL("https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fq_70%2Cc_zoom%2Cw_640%2Fimages%2F20200208%2F281ed353179745369814955cb31b02f0.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642953563&t=0d19afab90e64e4e7f7bc0d0a775f27a");
            productList.add(product1);
            Product product2 = new Product();
            product2.setName("外星人电脑");
            product2.setPrice(40000);
            product2.setURL("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp7.itc.cn%2Fq_70%2Fimages01%2F20210525%2Fa28b2807ad8f425198d51a69446711f4.jpeg&refer=http%3A%2F%2Fp7.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642985623&t=74a2f7f5df24fe7e1e9c528088283751");
            productList.add(product2);
        }
//        adapter.notifyItemRangeChanged(0, productList.size());
    }
}